import { View, Text, Button, Input, Textarea, Picker, Image } from '@tarojs/components'
import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { ui } from '../../../utils/platform'
import { useAuth } from '../../../contexts/AuthContext'
import { updateUserDetail } from '../../../services/api'
import dayjs from 'dayjs'
import './index.less'
import defaultAvatar from '../../../assets/images/default-avatar.png'

export default function RegisterStep() {
  const { userInfo, updateUserInfo, updatePhoto, updateIntroduce, fetchUserInfo } = useAuth()
  const [currentStep, setCurrentStep] = useState(1)
  const [loading, setLoading] = useState(false)
  
  // 基本信息状态
  const [introduce, setIntroduce] = useState('')
  const [photoPath, setPhotoPath] = useState('')
  const [photoUrl, setPhotoUrl] = useState('')
  
  // 详细信息状态
  const [detailInfo, setDetailInfo] = useState({
    nickName: '',
    medicalHistory: '',
    sex: null,
    birthday: '',
    zodiac: '',
    personalityType: '',
    hobbies: '',
    country: '中国',
    province: '',
    city: ''
  })
  
  const [showDatePicker, setShowDatePicker] = useState(false)
  const [selectedDate, setSelectedDate] = useState('')

  // 步骤配置
  const steps = [
    { title: '基本信息', desc: '设置头像和个人简介' },
    { title: '个人资料', desc: '完善详细个人信息' },
    { title: '完成', desc: '信息完善完成' }
  ]

  // 字段配置
  const fieldConfig = {
    sex: { 
      label: '性别', 
      type: 'select', 
      options: [{ value: 1, label: '男' }, { value: 0, label: '女' }] 
    },
    zodiac: { 
      label: '星座', 
      type: 'select', 
      options: [
        { value: '白羊座', label: '白羊座' },
        { value: '金牛座', label: '金牛座' },
        { value: '双子座', label: '双子座' },
        { value: '巨蟹座', label: '巨蟹座' },
        { value: '狮子座', label: '狮子座' },
        { value: '处女座', label: '处女座' },
        { value: '天秤座', label: '天秤座' },
        { value: '天蝎座', label: '天蝎座' },
        { value: '射手座', label: '射手座' },
        { value: '摩羯座', label: '摩羯座' },
        { value: '水瓶座', label: '水瓶座' },
        { value: '双鱼座', label: '双鱼座' }
      ]
    },
    personalityType: { 
      label: '性格类型', 
      type: 'select', 
      options: [
        { value: 'INTJ', label: 'INTJ - 建筑师' },
        { value: 'INTP', label: 'INTP - 思想家' },
        { value: 'ENTJ', label: 'ENTJ - 指挥官' },
        { value: 'ENTP', label: 'ENTP - 辩论家' },
        { value: 'INFJ', label: 'INFJ - 提倡者' },
        { value: 'INFP', label: 'INFP - 调停者' },
        { value: 'ENFJ', label: 'ENFJ - 主人公' },
        { value: 'ENFP', label: 'ENFP - 竞选者' },
        { value: 'ISTJ', label: 'ISTJ - 物流师' },
        { value: 'ISFJ', label: 'ISFJ - 守护者' },
        { value: 'ESTJ', label: 'ESTJ - 总经理' },
        { value: 'ESFJ', label: 'ESFJ - 执政官' },
        { value: 'ISTP', label: 'ISTP - 鉴赏家' },
        { value: 'ISFP', label: 'ISFP - 探险家' },
        { value: 'ESTP', label: 'ESTP - 企业家' },
        { value: 'ESFP', label: 'ESFP - 娱乐家' }
      ]
    }
  }

  // 根据生日计算年龄
  const calculateAge = (birthday) => {
    if (!birthday) return null
    const birthDate = dayjs(birthday)
    const today = dayjs()
    let age = today.year() - birthDate.year()
    const monthDiff = today.month() - birthDate.month()
    if (monthDiff < 0 || (monthDiff === 0 && today.date() < birthDate.date())) {
      age--
    }
    return age
  }

  // 选择图片
  const handleChooseImage = async () => {
    try {
      const res = await ui.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      })
      
      const tempFilePath = res.tempFilePaths[0]
      setPhotoPath(tempFilePath)
      setPhotoUrl(tempFilePath)
    } catch (error) {
      console.error('选择图片失败:', error)
      ui.showToast({
        title: '选择图片失败',
        icon: 'none',
        duration: 2000
      })
    }
  }

  // 保存基本信息
  const handleSaveBasicInfo = async () => {
    setLoading(true)
    try {
      // 检查是否有内容需要保存
      const hasPhoto = photoPath && photoPath.trim() !== ''
      const hasIntroduce = introduce && introduce.trim() !== ''
      
      if (!hasPhoto && !hasIntroduce) {
        // 如果没有任何内容，直接跳到下一步
        setCurrentStep(2)
        return
      }
      
      let result = { success: true }
      
      // 只上传头像，不调用introduce相关API
       if (hasPhoto && !hasIntroduce) {
         result = await updatePhoto(photoPath)
       }
       // 只更新简介
       else if (!hasPhoto && hasIntroduce) {
         result = await updateIntroduce(introduce)
       }
      // 同时更新头像和简介
      else if (hasPhoto && hasIntroduce) {
        result = await updateUserInfo(introduce, photoPath)
      }
      
      if (result.success) {
        ui.showToast({
          title: '基本信息保存成功',
          icon: 'success',
          duration: 1500
        })
        setCurrentStep(2)
      } else {
        // 显示后端返回的具体错误信息
        const errorMessage = result?.message || result?.msg || result?.error || '保存失败'
        ui.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('保存基本信息失败:', error)
      // 显示具体的错误信息
      const errorMessage = error?.response?.data?.message || error?.message || '保存失败'
      Taro.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 2000
      })
    } finally {
      setLoading(false)
    }
  }

  // 保存详细信息
  const handleSaveDetailInfo = async () => {
    setLoading(true)
    try {
      // 如果有生日，自动计算年龄
      const updateData = { ...detailInfo }
      if (updateData.birthday) {
        const calculatedAge = calculateAge(updateData.birthday)
        if (calculatedAge !== null) {
          updateData.age = calculatedAge
        }
      }
      
      const result = await updateUserDetail(updateData)
      if (result.code === 100200) {
        Taro.showToast({
          title: '详细信息保存成功',
          icon: 'success',
          duration: 1500
        })
        setCurrentStep(3)
      } else {
        // 显示后端返回的具体错误信息
        const errorMessage = result?.msg || result?.message || result?.error || '保存失败'
        Taro.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('保存详细信息失败:', error)
      // 显示具体的错误信息
      const errorMessage = error?.response?.data?.message || error?.response?.data?.msg || error?.message || '保存失败'
      Taro.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 2000
      })
    } finally {
      setLoading(false)
    }
  }

  // 跳过当前步骤
  const handleSkipStep = () => {
    if (currentStep === 1) {
      setCurrentStep(2)
    } else if (currentStep === 2) {
      setCurrentStep(3)
    }
  }

  // 完成并跳转到首页
  const handleComplete = () => {
    Taro.showToast({
      title: '欢迎使用！',
      icon: 'success',
      duration: 1500
    })
    
    setTimeout(() => {
      Taro.reLaunch({
        url: '/pages/index/index'
      })
    }, 1000)
  }

  // 更新详细信息字段
  const updateDetailField = (field, value) => {
    setDetailInfo(prev => ({
      ...prev,
      [field]: value
    }))
  }

  // 获取显示值
  const getDisplayValue = (field, value) => {
    const config = fieldConfig[field]
    if (config && config.type === 'select' && config.options) {
      const option = config.options.find(opt => opt.value == value)
      return option ? option.label : '请选择'
    }
    return value || ''
  }

  return (
    <View className='register-step-container'>
      {/* 步骤指示器 */}
      <View className='step-indicator'>
        {steps.map((step, index) => (
          <View key={index} className={`step-item ${currentStep > index ? 'completed' : ''} ${currentStep === index + 1 ? 'active' : ''}`}>
            <View className='step-number'>
              {currentStep > index + 1 ? '✓' : index + 1}
            </View>
            <Text className='step-title'>{step.title}</Text>
          </View>
        ))}
      </View>

      {/* 步骤内容 */}
      <View className='step-content'>
        {currentStep === 1 && (
          <View className='basic-info-step'>
            <Text className='step-desc'>设置您的头像和个人简介，让其他人更好地了解您</Text>
            
            <View className='avatar-section'>
              <Text className='section-title'>头像</Text>
              <View className='avatar-container' onClick={handleChooseImage}>
                <Image 
                  className='avatar-image' 
                  src={photoUrl || userInfo?.photo || defaultAvatar} 
                />
                <View className='avatar-edit-overlay'>点击更换头像</View>
              </View>
            </View>
            
            <View className='intro-section'>
              <Text className='section-title'>个人简介</Text>
              <Textarea
                className='intro-textarea'
                value={introduce}
                onInput={e => setIntroduce(e.detail.value)}
                placeholder='写一段简介介绍自己吧...'
                maxlength={200}
              />
              <Text className='char-count'>{introduce.length}/200</Text>
            </View>
            
            <View className='step-actions'>
              <Button className='skip-button' onClick={handleSkipStep}>跳过</Button>
              <Button className='next-button' loading={loading} onClick={handleSaveBasicInfo}>
                下一步
              </Button>
            </View>
          </View>
        )}

        {currentStep === 2 && (
          <View className='detail-info-step'>
            <Text className='step-desc'>完善您的详细信息，帮助AI更好地了解您</Text>
            
            <View className='form-section'>
              <View className='form-item'>
                <Text className='form-label'>昵称</Text>
                <Input
                  className='form-input'
                  value={detailInfo.nickName}
                  onInput={e => updateDetailField('nickName', e.detail.value)}
                  placeholder='请输入昵称'
                />
              </View>
              
              <View className='form-item'>
                <Text className='form-label'>过往病史</Text>
                <Textarea
                  className='form-textarea'
                  value={detailInfo.medicalHistory}
                  onInput={e => updateDetailField('medicalHistory', e.detail.value)}
                  placeholder='请输入过往病史（如有）'
                  maxlength={500}
                />
              </View>
              
              <View className='form-item'>
                <Text className='form-label'>性别</Text>
                <Picker
                  mode='selector'
                  range={fieldConfig.sex.options.map(opt => opt.label)}
                  value={fieldConfig.sex.options.findIndex(opt => opt.value === detailInfo.sex)}
                  onChange={e => {
                    const selectedOption = fieldConfig.sex.options[e.detail.value]
                    updateDetailField('sex', selectedOption.value)
                  }}
                >
                  <View className='picker-view'>
                    <Text className={detailInfo.sex !== null ? 'picker-text' : 'picker-placeholder'}>
                      {getDisplayValue('sex', detailInfo.sex) || '请选择性别'}
                    </Text>
                    <Text className='picker-arrow'>›</Text>
                  </View>
                </Picker>
              </View>
              
              <View className='form-item'>
                <Text className='form-label'>生日</Text>
                <Picker
                  mode='date'
                  value={detailInfo.birthday}
                  start="1900-01-01"
                  end={dayjs().format('YYYY-MM-DD')}
                  onChange={e => updateDetailField('birthday', e.detail.value)}
                >
                  <View className='picker-view'>
                    <Text className={detailInfo.birthday ? 'picker-text' : 'picker-placeholder'}>
                      {detailInfo.birthday ? dayjs(detailInfo.birthday).format('YYYY年MM月DD日') : '请选择生日'}
                    </Text>
                    <Text className='picker-arrow'>›</Text>
                  </View>
                </Picker>
              </View>
              
              <View className='form-item'>
                <Text className='form-label'>星座</Text>
                <Picker
                  mode='selector'
                  range={fieldConfig.zodiac.options.map(opt => opt.label)}
                  value={fieldConfig.zodiac.options.findIndex(opt => opt.value === detailInfo.zodiac)}
                  onChange={e => {
                    const selectedOption = fieldConfig.zodiac.options[e.detail.value]
                    updateDetailField('zodiac', selectedOption.value)
                  }}
                >
                  <View className='picker-view'>
                    <Text className={detailInfo.zodiac ? 'picker-text' : 'picker-placeholder'}>
                      {detailInfo.zodiac || '请选择星座'}
                    </Text>
                    <Text className='picker-arrow'>›</Text>
                  </View>
                </Picker>
              </View>
              
              <View className='form-item'>
                <Text className='form-label'>性格类型</Text>
                <Picker
                  mode='selector'
                  range={fieldConfig.personalityType.options.map(opt => opt.label)}
                  value={fieldConfig.personalityType.options.findIndex(opt => opt.value === detailInfo.personalityType)}
                  onChange={e => {
                    const selectedOption = fieldConfig.personalityType.options[e.detail.value]
                    updateDetailField('personalityType', selectedOption.value)
                  }}
                >
                  <View className='picker-view'>
                    <Text className={detailInfo.personalityType ? 'picker-text' : 'picker-placeholder'}>
                      {getDisplayValue('personalityType', detailInfo.personalityType) || '请选择性格类型'}
                    </Text>
                    <Text className='picker-arrow'>›</Text>
                  </View>
                </Picker>
              </View>
              
              <View className='form-item'>
                <Text className='form-label'>兴趣爱好</Text>
                <Textarea
                  className='form-textarea'
                  value={detailInfo.hobbies}
                  onInput={e => updateDetailField('hobbies', e.detail.value)}
                  placeholder='请输入您的兴趣爱好'
                  maxlength={200}
                />
              </View>
              
              <View className='form-item'>
                <Text className='form-label'>省份</Text>
                <Input
                  className='form-input'
                  value={detailInfo.province}
                  onInput={e => updateDetailField('province', e.detail.value)}
                  placeholder='请输入省份'
                />
              </View>
              
              <View className='form-item'>
                <Text className='form-label'>城市</Text>
                <Input
                  className='form-input'
                  value={detailInfo.city}
                  onInput={e => updateDetailField('city', e.detail.value)}
                  placeholder='请输入城市'
                />
              </View>
            </View>
            
            <View className='step-actions'>
              <Button className='skip-button' onClick={handleSkipStep}>跳过</Button>
              <Button className='next-button' loading={loading} onClick={handleSaveDetailInfo}>
                完成
              </Button>
            </View>
          </View>
        )}

        {currentStep === 3 && (
          <View className='complete-step'>
            <View className='success-icon'>✓</View>
            <Text className='success-title'>信息完善完成！</Text>
            <Text className='success-desc'>您的个人信息已经设置完成，现在可以开始使用AI情感分析功能了</Text>    
            <View className='complete-actions'>
              <Button className='complete-button' onClick={handleComplete}>
                开始使用
              </Button>
            </View>
          </View>
        )}
      </View>
    </View>
  )
}